<?php
/**
 * @Description: 任教学科
 * @Author: kzj
 * @datetime: 2023-02-24
 */
namespace App\Services\Education;

use App\Http\Controllers\Excel\ExcelExport;
use App\Http\Controllers\Excel\ExcelImport;
use App\Models\ActivityInfo;
use App\Models\DictionaryItem;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;


/**
 * 实践活动导出 (服务)
 */
class PlanService
{
    /** @var \App\Repositories\System\ActivityRepository $activityRepository */
    private $activityRepository;
    /** @var \App\Repositories\System\ParticipantRepository $participantRepository */
    private $participantRepository;
    /** @var \App\Repositories\System\SystemTaskRepository $systemTaskRepository */
    private $systemTaskRepository;

    public function __construct()
    {
        $this->activityRepository = app('activityRepository');
        $this->participantRepository = app('participantRepository');
        $this->systemTaskRepository = app('systemTaskRepository');
        $this->zm_gkk_category = [1 => '计划' , 2 => '总结'];
    }

    /*
     * @Description: 社会实践导出
     * @Author:  Kzj
     * @Date: 2023-11-17 14:43:04
     */
    public function export($request)
    {
        $formKey = NULL;
        $termId = 0;
        $name = '';
        $status = '';
        $hostName = ''; //主持人
        $beginDate = '';
        $endDate = '';
        $joinName = '';
        $creatorName = '';
        $rangeDate = [];
        $jsonSearch = [];
        $hasSearch = false;
        $zm_gkk_category = '';
        $user = Auth::user();
        // dd($roleType);


        $formKey = $request['form_key'] ?? '';
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $hasSearch = true;
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $hasSearch = true;
            $name = $request['search']['name'];
        }
        if (isset($request['search']['status']) && !empty($request['search']['status'])){
            $hasSearch = true;
            $status = $request['search']['status'];
        }
        if (isset($request['search']['host_name']) && !empty($request['search']['host_name'])){
            $hasSearch = true;
            $hostName = $request['search']['host_name'];
        }
        if (isset($request['search']['begin_date']) && !empty($request['search']['begin_date'])){
            $hasSearch = true;
            $beginDate = $request['search']['begin_date'];
        }
        if (isset($request['search']['end_date']) && !empty($request['search']['end_date'])){
            $hasSearch = true;
            $endDate = $request['search']['end_date'];
        }
        //通过json的类型及optionId值进行查询
        if (isset($request['json_search']['pubications_publish_type'] )&& !empty($request['json_search']['pubications_publish_type'])){
            $hasSearch = true;
            $jsonSearch['pubications_publish_type'] = $request['json_search']['pubications_publish_type'];
        }
        if (isset($request['search']['level'] )&& !empty($request['search']['level'])){
            $hasSearch = true;
            $jsonSearch['level'] = $request['search']['level'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $hasSearch = true;
            $jsonSearch['course'] = $request['search']['course'];
        }
        if (isset($request['search']['grade'] )&& !empty($request['search']['grade'])){
            $hasSearch = true;
            $jsonSearch['grade'] = $request['search']['grade'];
        }
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $hasSearch = true;
            $jsonSearch['class_item'] = $request['search']['class_item'];
        }
        if (isset($request['search']['category'] )&& !empty($request['search']['category'])){
            $hasSearch = true;
            $jsonSearch['category'] = $request['search']['category'];
        }
        if (isset($request['search']['reception_class'] )&& !empty($request['search']['reception_class'])){
            $hasSearch = true;
            $jsonSearch['reception_class'] = $request['search']['reception_class'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $hasSearch = true;
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        if (isset($request['search']['join_name'] )&& !empty($request['search']['join_name'])){
            $hasSearch = true;
            $joinName = $request['search']['join_name'];
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $hasSearch = true;
            $creatorName = $request['search']['creator_name'];
        }
        $status = 'PASS';//导出的数据均为审核通过的

        if (isset($request['search']['zm_gkk_category'] )&& !empty($request['search']['zm_gkk_category'])){
            $zm_gkk_category = $request['search']['zm_gkk_category'];
        }
        $user = Auth::user();
        $viewAll = $this->activityRepository->getViewPower($request['form_key']);

        $output = ActivityInfo::select('activity_info.*', 'b.status')
            ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->leftJoin('participant as p', 'activity_info.id', '=', 'p.activity_info_id')
            ->manageable()
            ->when($formKey, function($q) use($formKey) {
                if(is_array($formKey)) {
                    $q->whereIn('activity_info.activity_category', $formKey);
                } else {
                    $q->where('activity_info.activity_category', $formKey);
                }
            })
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('activity_info.data_version_id', $termId);
                });
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('activity_info.begin_date', '<=', $rangeDate[0])->where('activity_info.end_date', '>=', $rangeDate[1]);
            })
            ->when($hostName, function($q) use($hostName) {
                $q->whereHas('compereUser', function ($query) use($hostName) {
                    $query->where('nickname', 'like', '%' . $hostName . '%');
                });
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when($status, function($q) use($status) {
                $q->where('b.status', '=', $status);
            })
            ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'instance:id,status')
            ->where('activity_info.deleted', 0)
            ->orderBy('activity_info.id', 'desc')
            ->get();
            //dd(DB::getQueryLog());
        //var_dump($output->toArray());
        $title = ['学年学期','类型','创建人','创建日期'];
        $exportData = [];
        foreach($output as $k => $v){
            $item = [
                'term' => $v->data_version_id ? $v->term->title : '',
                'name' => $this->zm_gkk_category[$v->zm_gkk_category] ?? '-',
                'creator' => !empty($v->creator) ? $v->creator->nickname : '',
                'created_at' => $v->created_at,
            ];

            $exportData[] = $item;
        }
        array_unshift($exportData, $title);

        $fileName = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($exportData), $fileName, 'excel');

        $result['file_name'] = $fileName;

        return $result;
    }



}
